class Solution {
public:
    int getLength(ListNode* head){
        int n = 0;
        while(head){
            head = head->next;
            n++;
        }
        return n;
    }

    ListNode* rotateRight(ListNode* head, int k) {
        if(head == NULL) return head;
        int n = getLength(head);
        k %= n;
        if(k == 0) return head;
        ListNode *p = head;
        ListNode *q = head;
        for(int i = 0; i < k; i++) q = q->next;
        while(q->next){
            q = q->next;
            p = p->next;
        }
        q->next = head;
        head = p->next;
        p->next = NULL;
        return head;
    }
};